package cn.wolfcode.interceptor;

import cn.wolfcode.controller.JsonResult;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.如果登录的用户是管理员,直接放行
        Employee employee = UserContext.getCurrentUser();
        if (employee.isAdmin()) {
            return true;
        }
        //如果不是管理员,获取当前要执行的控制器的处理方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        RequiredPermission annotation = (method.getMethodAnnotation(RequiredPermission.class));
        if (annotation == null) {
            return true;
        }

        //
        //List<String> permissions = (List<String>) request.getSession().getAttribute("EXPRESSION_IN_SESSION");
        List<String> permissions = UserContext.getExpressions();
        if (permissions.contains(annotation.expression())) {
            return true;
        }
        if (!method.hasMethodAnnotation(ResponseBody.class)) {
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request, response);
        } else {
            JsonResult json = new JsonResult(false, "您没有操作权限");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(json));
        }
        return false;
    }
}
